import { Controller, Get, Post, Body, Query, Req, Session } from '@nestjs/common';
import { TaskService } from './task.service';
import { MessageService } from '../message/message.service';
import { LogService } from '../log/log.service';

@Controller('task')
export class TaskController {
  constructor(
    private readonly taskService: TaskService,
    private readonly messageService: MessageService,
    private readonly logService: LogService
  ) { }

  @Get('getTask')
  async getTask(@Query('robotId') robotId: string, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    const tasks = await this.taskService.findAll(robotId ? parseInt(robotId, 10) : undefined);
    return {
      code: 0,
      data: tasks,
      msg: 'success'
    };
  }

  @Post('createMessage')
  async createMessage(@Body() createMessageDto: any, @Session() session: Record<string, any>, @Req() req: any) {
    console.log('接收到的消息数据:', JSON.stringify(createMessageDto));
    console.log('消息内容类型:', typeof createMessageDto.msgContent);
    console.log('消息内容值:', createMessageDto.msgContent);
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      createMessageDto.userId = session.userId;
      const result = await this.taskService.createMessage(createMessageDto);

      // 保存日志记录
      try {
        // 解析消息内容以获取文本
        let parsedContent;
        try {
          parsedContent = typeof createMessageDto.msgContent === 'string'
            ? JSON.parse(createMessageDto.msgContent)
            : createMessageDto.msgContent;
        } catch (e) {
          parsedContent = { content: createMessageDto.msgContent };
        }

        await this.logService.create({
          robotId: createMessageDto.robotId,
          userId: session.userId,
          methond: '0', // 手动发送
          msgType: 'text',
          msgContent: typeof createMessageDto.msgContent === 'string'
            ? createMessageDto.msgContent
            : JSON.stringify(createMessageDto.msgContent),
          remark: parsedContent.content.substring(0, 20) || '无内容',
          status: result.errcode === 0 ? '1' : '0' // 根据API返回设置成功/失败
        });
      } catch (err) {
        console.error('保存日志记录失败:', err);
        // 不中断流程，继续返回成功
      }

      // 同时保存到消息历史记录
      if (createMessageDto.save) {
        try {
          // 解析消息内容以获取文本
          let parsedContent;
          try {
            parsedContent = typeof createMessageDto.msgContent === 'string'
              ? JSON.parse(createMessageDto.msgContent)
              : createMessageDto.msgContent;
          } catch (e) {
            parsedContent = { content: createMessageDto.msgContent };
          }

          const message = await this.messageService.create({
            robotId: createMessageDto.robotId,
            userId: session.userId,
            msgType: 'text',
            msgContent: typeof createMessageDto.msgContent === 'string'
              ? createMessageDto.msgContent
              : JSON.stringify(createMessageDto.msgContent),
            remark: parsedContent.content.substring(0, 20) || '无内容'
          });
          console.log('保存消息记录成功:', message.id);
        } catch (err) {
          console.error('保存消息历史失败:', err);
          // 不中断流程，继续返回成功
        }
      }

      return {
        code: 0,
        data: result,
        msg: 'success'
      };
    } catch (error) {
      console.error('发送消息错误:', error);
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('createTask')
  async createTask(@Body() createTaskDto: any, @Session() session: Record<string, any>, @Req() req: any) {
    console.log('创建任务的数据:', JSON.stringify(createTaskDto));

    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      createTaskDto.userId = session.userId;
      const task = await this.taskService.createTask(createTaskDto);
      // 如果是一次性消息，并且执行时间是过去的时间，立即发送
      if (task.isOneTime && new Date(task.executeTime) <= new Date()) {
        try {
          await this.taskService.sendTaskMessage(task);
        } catch (sendError) {
          console.error('立即发送任务消息失败:', sendError);
        }
      }
      return {
        code: 0,
        data: task,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('createOneTime')
  async createOneTime(@Body() createOneTimeDto: any, @Session() session: Record<string, any>, @Req() req: any) {
    console.log('创建一次性任务的数据:', JSON.stringify(createOneTimeDto));

    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      createOneTimeDto.userId = session.userId;

      // 确保设置isOneTime=true
      const task = await this.taskService.createTask(createOneTimeDto);

      // 如果执行时间是过去的时间，立即发送
      if (new Date(task.executeTime) <= new Date()) {
        try {
          await this.taskService.sendTaskMessage(task);
        } catch (sendError) {
          console.error('立即发送一次性任务消息失败:', sendError);
        }
      }

      return {
        code: 0,
        data: task,
        msg: 'success'
      };
    } catch (error) {
      console.error('创建一次性任务失败:', error);
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('updateTask')
  async updateTask(@Body() updateTaskDto: any, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      const { id, ...taskData } = updateTaskDto;
      const task = await this.taskService.updateTask(id, taskData);
      return {
        code: 0,
        data: task,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }

  @Post('removeTask')
  async removeTask(@Body() body: { id: number }, @Session() session: Record<string, any>, @Req() req: any) {
    if (!session.userId) {
      return {
        code: 1,
        data: null,
        msg: '未登录'
      };
    }

    try {
      await this.taskService.removeTask(body.id);
      return {
        code: 0,
        data: null,
        msg: 'success'
      };
    } catch (error) {
      return {
        code: 1,
        data: null,
        msg: error.message
      };
    }
  }
} 